import pandas as pd
import re
import time
import os
import shutil
from pick_utils import ReMatchFunc, str_plus
from split_utils import special_split, rule_list_1


'''
提取“拆分后元数据内容”到对应字段
'''

def pick_1(operate_dir):
    # 读取配置文件 --------------------------------------
    # 只有功能1读取“原题名”存入“拆分后元数据内容”，其他程序都是读取“拆分后元数据内容”存入“拆分后元数据内容”
    source_title_col = '<作者>拆分后元数据内容'
    # -------------------------------------------------

    # 检测excel数量，只能放一个，当只有一个excel时，提取它的路径excel_path -------
    print('检查路径下的文件格式...')
    excel_name = None
    excel_count = 0
    file_list = os.listdir(operate_dir)
    for file in file_list:
        if file.endswith('.xlsx') or file.endswith('.xlx'):
            excel_count += 1
            excel_name = file
    if excel_count == 0:
        input('文件夹下没有excel，按任意键退出...')
        raise Exception(0)
    if excel_count > 1:
        input('只能放一个excel，按任意键退出...')
        raise Exception(0)

    # print(excel_name)
    # raise Exception(1212)
    # ----------------------------------------------------------------------
    # print(excel_path)
    # print(img_dir)

    # 读取excel ----------------------------------------
    excel_path = os.path.join(operate_dir, excel_name)
    # print(excel_path)
    try:
        df = pd.read_excel(excel_path)
        df = df.where(df.notnull(), None)
    except Exception as e:
        print(e)
        print('文件不存在或已损坏...')
        input('按任意键退出...')
        raise Exception('123')
    # -------------------------------------------------

    # 备份原始excel表 --------------------------------------------------------------
    print('备份excel...')
    bak_dir = '作者拆分前的备份'
    file_list = os.listdir(operate_dir)
    if bak_dir not in file_list:
        os.makedirs(os.path.join(operate_dir, bak_dir))
    bak_excel_path = os.path.join(os.path.join(operate_dir, bak_dir), excel_name)
    shutil.copyfile(excel_path, bak_excel_path)
    # -----------------------------------------------------------------------------

    # --------------------------------
    all_nomatch_list = []  # 未匹配到的数据
    all_other_countryside_list = []  # 外国国别/年代
    all_cn_countryside_list = []  # 中国国别/年代
    all_other_name_list = []  # 外国姓名
    all_cn_name_list = []  # 中国姓名
    all_zlfs_list = []  # 著录方式
    all_alias_list = []  # 别名
    # --------------------------------

    for i in range(df.shape[0]):

        # 源题名
        try:
            source_author = df.loc[i, source_title_col]
        except Exception as e:
            print(e)
            print('excel中好像没有“拆分后元数据内容”这一列')
            input('按任意键退出...')
            raise Exception('123')
        print(source_author)

        if not source_author:
            all_nomatch_list.append(None)  # 未匹配到的数据
            all_other_countryside_list.append(None)  # 外国国别/年代
            all_cn_countryside_list.append(None)    # 中国国别/年代
            all_other_name_list.append(None)   # 外国姓名
            all_cn_name_list.append(None)  # 中国姓名
            all_zlfs_list.append(None)  # 著录方式
            all_alias_list.append(None)  # 别名
        else:
            source_author = str(source_author)

            # 走正常流程拆 -------------------------------------------------------------------------

            split_list = source_author.split(';')

            # 外国国别提取 --------------------------
            other_countryside_list = ReMatchFunc.other_countryside(split_list)
            # print(countryside_list)
            other_countryside_str = ';'.join(other_countryside_list) if other_countryside_list else None
            all_other_countryside_list.append(other_countryside_str)
            # -----------------------------------

            # 国内朝代提取 --------------------------
            cn_countryside_list = ReMatchFunc.cn_countryside(split_list)
            # print(countryside_list)
            cn_countryside_str = ';'.join(cn_countryside_list) if cn_countryside_list else None
            all_cn_countryside_list.append(cn_countryside_str)
            # -----------------------------------

            # 国外姓名提取 -----------------------------------
            other_name_list = ReMatchFunc.other_name(split_list)
            # print(name_list)
            other_name_str = ';'.join(other_name_list) if other_name_list else None
            all_other_name_list.append(other_name_str)
            # -------------------------------------------

            # 国内姓名提取 -----------------------------------
            cn_name_list = ReMatchFunc.cn_name(split_list)
            # 剔除以匹配到的外国姓名
            cn_name_list = [cn_name for cn_name in cn_name_list if cn_name not in other_name_list]
            # print(name_list)
            cn_name_str = ';'.join(cn_name_list) if cn_name_list else None
            all_cn_name_list.append(cn_name_str)
            # -------------------------------------------

            # 著录方式提取 ------------------------------------------------------
            zlfs_list = ReMatchFunc.zlfs(split_list)
            # print(zlfs_list)
            zlfs_str = ';'.join(zlfs_list) if zlfs_list else None
            all_zlfs_list.append(zlfs_str)
            # ---------------------------------------------------------------

            # 别名提取 -------------------------------------------------------------------------
            alias_list = ReMatchFunc.alias(split_list)
            # print(alias_list)
            alias_str = ';'.join(alias_list) if alias_list else None
            all_alias_list.append(alias_str)
            # ---------------------------------------------------------------------------------

            # 未匹配到的数据提取 --------------------------------------------
            nomatch_list = []
            # print(zhengtiming_list, author_list, fencehao_list, fenceming_list, banbenbeizhu_list, banbenshuoming_list, bind_list, fujian_list, kaiben_list, congshuming_list, futiming_list, taozhuangshuliang_list)
            match_list = all_other_countryside_list + all_cn_countryside_list + all_other_name_list + all_cn_name_list + zlfs_list + alias_list
            for txt in split_list:
                if txt not in match_list:
                    nomatch_list.append(txt)
            nomatch_str = ';'.join(nomatch_list) if nomatch_list else None
            all_nomatch_list.append(nomatch_str)
            # -------------------------------------------------------------

            # ------------------------------------------------------------------------------------------

            print(i, split_list)

    # 打印拆分结果 ------------------
    print('all_nomatch_list: {}'.format(all_nomatch_list))
    print('all_other_countryside_list: {}'.format(all_other_countryside_list))
    print('all_cn_countryside_list: {}'.format(all_cn_countryside_list))
    print('all_other_name_list: {}'.format(all_other_name_list))
    print('all_cn_name_list: {}'.format(all_cn_name_list))
    print('all_zlfs_list: {}'.format(all_zlfs_list))
    print('all_alias_list: {}'.format(all_alias_list))
    # -----------------------------

    # 保存拆分结果 ----------------------------
    df.loc[:, '<作者>[拆分]未匹配到的数据'] = all_nomatch_list
    df.loc[:, '<作者>[拆分]国籍和年代（外国）'] = all_other_countryside_list
    df.loc[:, '<作者>[拆分]国籍和年代（中国）'] = all_cn_countryside_list
    df.loc[:, '<作者>[拆分]作者名称（外国）'] = all_other_name_list
    df.loc[:, '<作者>[拆分]作者名称（中国）'] = all_cn_name_list
    df.loc[:, '<作者>[拆分]作者其他名称'] = all_alias_list
    df.loc[:, '<作者>[拆分]著录方式'] = all_zlfs_list

    print('正在保存...')
    df.to_excel(excel_path, index=0)
    print('保存完成')
    # ---------------------------------------


if __name__ == '__main__':
    operate_dir = r'C:\Users\cxstar46\Desktop\正则表达式作者拆分测试'
    pick_1(operate_dir)

